<template>
  <div>
    <fc-designer ref="designer" height="80vh" @save="handleSave" :config="config"/>
  </div>
</template>

<script setup name="formBuild">
import { useRoute, useRouter } from "vue-router";
import { getCurrentInstance, reactive, ref, toRefs } from "vue";
import { saveForm } from "@/api/form.js";
import { ElMessage } from "element-plus";

const { proxy } = getCurrentInstance();
const route = useRoute();
const id = ref(route.params.id);

const buildForm = ref({});
const data = reactive({
  config: {
    showSaveBtn: true
  }
});
const { config } = toRefs(data);
const router = useRouter();

function handleSave() {
  if (!proxy.$refs.designer) {
    console.error("设计器引用未定义!");
    return;
  }

  // 将JSON对象转换为字符串再发送
  buildForm.value = {
    id: id.value,
    optionBuild: JSON.stringify(proxy.$refs.designer.getOptionsJson()),
    ruleBuild: JSON.stringify(proxy.$refs.designer.getJson())
  };


  saveForm(buildForm.value)
      .then(res => {
        if (res.code === 1) {
          ElMessage.success("保存成功");
        } else {
          ElMessage.error(res.msg);
        }
      })
      .catch(error => {
        console.error("保存失败", error);
        ElMessage.error("保存失败");
      });
}
</script>

